package LineCode.other.thread;

/**
 * @author senselyan
 * @Description: 两个线程，分别打印AB，其中线程A打印A，线程B打印B，各打印10次，使之出现ABABABABA.. 的效果
 * @date 2018/3/26 10:05
 */
public class PrintABABA_ {

    public static void main(String[] args) {

        final Print_ play = new Print_();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    play.print_A();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    play.print_B();
                }
            }
        }).start();
    }


    static class Print_ {

        private boolean flag = true;

        public synchronized void print_A () {
            if (!flag) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.print("A");
            flag = false;
            this.notify();
        }

        public synchronized void print_B () {
            if (flag) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.print("B");
            flag = true;
            this.notify();
        }
    }

}